package com.wiscamp.ninechapters.common.encrypt;

/**
 * MD5 Helper
 */
public class Md5Helper {

    private Md5Helper() {
    }

    private static final String HEX_CHARS = "0123456789ABCDEF";

    /**
     * 将16进制字符串转换成字节数组
     *
     * @param text
     * @return
     */

    public static byte[] hexStringToByte(String text) {
        int len = (text.length() / 2);
        byte[] result = new byte[len];
        char[] hexChars = text.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (HEX_CHARS.indexOf(hexChars[pos]) << 4
                    | HEX_CHARS.indexOf(hexChars[pos + 1]));
        }
        return result;
    }

    /**
     * 将指定byte数组转换成16进制字符串
     *
     * @param bytes
     * @return
     */

    public static String byteToHexString(byte[] bytes) {
        var buffer = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            var hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            buffer.append(hex.toUpperCase());
        }
        return buffer.toString();
    }
}
